/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.message;

import cn.easyplatform.lang.Lang;
import cn.easyplatform.utils.JmsUtils;
import cn.easyplatform.web.message.entity.Destination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.*;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public abstract class AbstractJmsConsumer implements MessageListener {

    protected final static Logger log = LoggerFactory.getLogger(AbstractJmsConsumer.class);

    private ConnectionFactory connectionFactory;

    private Connection connection;

    private Session session;

    private MessageConsumer consumer;

    protected Destination destination;

    public AbstractJmsConsumer(ConnectionFactory connectionFactory, Destination dest) {
        this.connectionFactory = connectionFactory;
        this.destination = dest;
        start();
    }


    private void start() {
        try {
            connection = connectionFactory.createConnection();
            connection.setExceptionListener(e -> {
                if (log.isErrorEnabled())
                    log.error("onException", e);
                close();
                Lang.sleep(5000);//每隔5秒重试
                start();
            });
            connection.start();
            session = connection.createSession(false, destination.getAcknowledge());
            javax.jms.Destination dest = null;
            if (destination.getName().endsWith("Queue"))
                dest = session.createQueue(destination.getName());
            else
                dest = session.createTopic(destination.getName());
            consumer = session.createConsumer(dest);
            consumer.setMessageListener(this);
            if (log.isDebugEnabled())
                log.debug("create jms consumer listener for {}", destination.getName());
        } catch (JMSException ex) {
            log.error("start", ex);
            close();
            Lang.sleep(5000);//每隔3秒重试
            start();
        }
    }

    /**
     * 关闭jms连接
     */
    public void close() {
        JmsUtils.close(connection, session, consumer);
        connection = null;
        session = null;
        if (log.isDebugEnabled())
            log.debug("close jms listener for {}", destination.getName());
    }
}
